<template>
  <div class="employees-detail-container">
    <div class="app-container">
      <el-card style="margin-bottom:15px;">
        <el-button type="primary" @click="$router.push('/employees')">返回</el-button>
      </el-card>
      <el-card>
        <el-tabs>
          <el-tab-pane label="登录账户设置">

            <!-- 放置表单 -->
            <el-form ref="userInfoForm" :model="userInfo" :rules="rules" label-width="120px" style="margin-left: 120px; margin-top:30px">
              <el-form-item label="姓名:" prop="username">
                <el-input v-model="userInfo.username" style="width:300px" />
              </el-form-item>
              <el-form-item label="新密码:" prop="showPassword">
                <el-input v-model="userInfo.showPassword" style="width:300px" type="password" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="updateUserInfo">更新</el-button>
                <div style="color:red;">不建议修改，谨慎操作！</div>
              </el-form-item>
            </el-form>
          </el-tab-pane>

          <el-tab-pane label="个人详情">
            <userInfo />
          </el-tab-pane>

          <el-tab-pane label="岗位信息">
            <jobInfo />
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>
  </div>
</template>

<script>
// 获取员工基本信息（包含头像）
import { getStaffBaseInfoRequest } from '@/api/user'
// 修改员工基本信息
import { changeEmployeesInfoRequest } from '@/api/employees'
// 个人信息栏组件
import userInfo from './components/user-info.vue'
// 岗位信息栏组件
import jobInfo from './components/job-info.vue'

export default {
  name: 'EmployeesDetail',
  components: {
    userInfo,
    jobInfo
  },

  data() {
    return {
      userInfo: {
        id: '',
        username: '',
        // 展示用的密码，为了不与传过来的重名，防止用户修改
        showPassword: ''
      },
      rules: {
        username: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
        showPassword: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { min: 6, max: 9, message: '密码长度6-9位', trigger: 'blur' }
        ]
      }
    }
  },

  computed: {
    userId() {
      return this.$route.params.id
    }
  },

  created() {
    this.getStaffBaseInfo()
  },

  methods: {
    // 获取用户基本信息并回显用户信息表单
    async getStaffBaseInfo() {
      const { data } = await getStaffBaseInfoRequest(this.userId)
      this.userInfo.username = data.username
      this.userInfo.id = data.id
    },
    // 更新用户信息：
    updateUserInfo() {
      this.$refs.userInfoForm.validate(async(valid) => {
        if (!valid) return
        if (valid) {
          // 发起请求：更新数据
          // const { data } = await changeEmployeesInfoRequest({ ...this.userInfo, password: this.userInfo.showPassword })
          try {
            await changeEmployeesInfoRequest(this.userInfo)
            this.$message.success('修改成功')
          } catch (error) {
            console.log(error.message)
          }
        }
      })
    }
  }
}
</script>
